package com.netforce.web.admin.mvc;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.netforce.data.source.Connection;
import com.netforce.data.source.DataSource;
import com.netforce.util.io.IoManager;

public interface ConnectionController
{
  @RequestMapping(value = "/", method = RequestMethod.GET)
  public String viewIndex(HttpServletRequest aRequest, HttpServletResponse aResponse) throws Exception;

  @RequestMapping(value = "/authentication.do", method = RequestMethod.GET)
  public void doAuthentication(HttpServletRequest aRequest, HttpServletResponse aResponse) throws Exception;

  @RequestMapping(value = "/connection.do", method = RequestMethod.GET)
  public String doConnection(HttpServletRequest aRequest, HttpServletResponse aResponse, String aCode) throws Exception;

  @Controller
  public class DefaultConnectionController implements ConnectionController
  {
    @Override
    public String viewIndex(HttpServletRequest aRequest, HttpServletResponse aResponse) throws Exception
    {
      Connection connection = (Connection)aRequest.getSession().getAttribute("connection");
      if (connection != null)
      {
        Method[] testMethods = TestController.class.getDeclaredMethods();
        Collection<String> testPaths = new Vector<>();
        for (Method testMethod : testMethods)
        {
          RequestMapping requestMapping = testMethod.getAnnotation(RequestMapping.class);
          for (String value : requestMapping.value())
          {
            testPaths.add(value);
          }
        }
        aRequest.setAttribute("connected", true);
        aRequest.setAttribute("testPaths", testPaths);
      }
      else
      {
        aRequest.setAttribute("connected", false);
      }
      return "/views/index.jsp";
    }
    @Override
    public void doAuthentication(HttpServletRequest aRequest, HttpServletResponse aResponse) throws Exception
    {
      IoManager.copy(DataSource.authenticate(), aResponse.getOutputStream());
    }

    @Override
    public String doConnection(HttpServletRequest aRequest, HttpServletResponse aResponse, @RequestParam("code") String aCode) throws Exception
    {
      aRequest.getSession().setAttribute("connection", DataSource.connect(aCode));
      return "/";
    }

    @Autowired
    protected DataSource DataSource;
    @Autowired
    protected IoManager IoManager;
  }
}
